package com.datastructure.test.LowestCommonAncestor;

import java.util.Stack;

/**
 * 寻找两个节点的最近节点
 */
public class LowestCommonAncestor {
    public int lowestCommonAncestor (TreeNode root, int o1, int o2) {
        // write code here
        Stack<TreeNode>o1Path=new Stack();
        Stack<TreeNode>o2Path=new Stack();
        getPath(root,o1,o1Path);
        getPath(root,o2,o2Path);
        int father=root.val;//第一个元素必定是root，两个栈第一个元素必相等
        while(!(o1Path.isEmpty()||o2Path.isEmpty())){
            int f1=o1Path.pop().val;
            int f2=o2Path.pop().val;
            if(f1!=f2)
                break;
            else
                father=f1;
        }
        return father;
    }
    boolean getPath(TreeNode root, int target, Stack<TreeNode> pathStack){
        if(root==null)return false;
        if(root.val==target//重点在于这个三合一的判定条件
                ||getPath(root.left,target,pathStack)
                ||getPath(root.right,target,pathStack)){
            System.out.print(root.val+" ");
            pathStack.push(root);
            return true;
        }
        return false;
    }

    public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
  }
}
